<template>
  <div class="add-new-good">
    <div class="edit">
      <el-scrollbar height="600px">
        <div class="title">上架商品</div>
        <div class="images">
          <div class="sub-title">编辑图片({{ goodsInfo.images.length }} /8)</div>
          <el-upload
            v-model:file-list="goodsInfo.images"
            action="#"
            list-type="picture-card"
            :disabled="goodsInfo.images.length >= 8"
            :on-change="uploadImages"
            :auto-upload="false"
          >
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </div>
        <div class="description">
          <div class="sub-title">商品参数</div>
          <el-form label-width="auto" style="width: 350px" :model="goodsInfo" :rules="rules">
            <!-- 商品名称 -->
            <el-form-item label="商品名称" prop="title">
              <el-input
                v-model="goodsInfo.name"
                placeholder="在这里填写商品名称"
                maxlength="20"
                show-word-limit
              />
            </el-form-item>
            <!-- 商品描述 -->
            <el-form-item label="商品描述" prop="description">
              <el-input
                v-model="goodsInfo.description"
                class="description"
                autosize
                maxlength="500"
                show-word-limit
                clearable
                placeholder="在这里描述商品特征"
              />
            </el-form-item>
            <!-- 商品价格 -->
            <el-form-item label="商品价格">
              <el-input-number v-model="goodsInfo.price" :precision="2" :min="0">
                <template #prefix>
                  <span>￥</span>
                </template>
              </el-input-number>
            </el-form-item>
            <!-- 所需积分 -->
            <el-form-item label="所需积分">
              <el-input-number v-model="goodsInfo.integral" :min="0">
                <template #prefix>
                  <span>∫</span>
                </template>
              </el-input-number>
            </el-form-item>
            <!-- 标签列 -->
            <el-form-item label="标签">
              <div class="tags">
                <el-tag
                  v-for="tag in goodsInfo.tags"
                  :key="tag"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(tag)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  v-if="tagVisible"
                  ref="tagRef"
                  v-model="tag"
                  style="max-width: 100px"
                  class="w-20"
                  size="small"
                  maxlength="10"
                  show-word-limit
                  @keyup.enter="addNewTag"
                />
                <el-button
                  v-if="!tagVisible && goodsInfo.tags.length < 3"
                  class="button-new-tag"
                  size="small"
                  @click="tagVisible = true"
                >
                  + 点击新增标签
                </el-button>
              </div>
            </el-form-item>
            <!-- 设置上架数量 -->
            <el-form-item label="上架数量">
              <el-input-number v-model="goodsInfo.number" :min="1" :max="999" />
            </el-form-item>
            <!-- 发布身份 -->
            <el-form-item label="发布身份">
              <el-select v-model="goodsInfo.identityId" placeholder="发布身份" style="width: 240px">
                <el-option
                  v-for="item in identities"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <el-divider />
          <span class="description">
            <span style="font-size: 16px">用户须知：</span>
            <br />
            1.用户可以为商品上传至少一张且最多八张图片，并且默认第一张为封面，用户可以根据需要进行调整。
            <br />
            2.用户可以设置金额￥为0或者兑换积分∫为0，但不能同时设成0，设成0的一项说明购买产品不额外扣去购买用户费用或积分（设置为负数则自动置0）。
            <br />
            3.用户最多可以上传三个标签，标签更有利于其他用户查找商品。
            <br />
            4.发布身份可以设置成个人或是其他已有的发布身份，若发布身份为个人，则商品数量最多设置为10。
          </span>
          <div class="buttons">
            <el-button type="primary" @click="addNewGoods(0)">发布</el-button>
            <el-button @click="addNewGoods(1)">保存</el-button>
          </div>
        </div>
      </el-scrollbar>
    </div>
  </div>
</template>

<script setup>
import { startLoading, stopLoading } from '@/utils/loading'
import { addGoods, getIdentityPreview } from '@/api/shop'
import { ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores'

const router = useRouter()

const useStore = useUserStore()

// 表单校验
const rules = {
  name: [
    { required: true, message: '请输入商品名字', trigger: 'blur' },
    { min: 1, max: 20, message: '标题字数为1~20字之间', trigger: 'blur' },
  ],
  description: [
    { required: true, message: '请输入商品描述', trigger: 'blur' },
    { min: 1, max: 500, message: '标题字数为1~500字之间', trigger: 'blur' },
  ],
}

// 表单数据
const goodsInfo = ref({
  name: '',
  description: '',
  price: 0,
  integral: 0,
  images: [],
  tags: [],
  number: 1,
  identityId: '',
})

// 身份数组
const identities = ref([])

// 获取所有身份
const getIdentities = async () => {
  let { data } = (await getIdentityPreview()).data
  data = [...[{ id: '0', name: '个人' }], ...data]
  identities.value = data
}

getIdentities()

// 上传图片
const uploadImages = (file) => {
  if (goodsInfo.value.images.length >= 8) {
    ElNotification({
      title: '提示',
      message: '上传图片数量不能超过8张!',
      type: 'warning',
    })
    return false
  }
  // 判断格式
  const isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png'
  if (!isJPG) {
    ElNotification({
      title: '提示',
      message: '上传图片只能是 JPG、PNG 格式!',
      type: 'warning',
    })
    return false
  }
  // 判断大小
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElNotification({
      title: '提示',
      message: '上传图片大小不能超过10MB',
      type: 'warning',
    })
    return false
  }
  // file.raw才是图片
  goodsInfo.value.images.push(file)
}

// 标签
const tag = ref('')

const tagVisible = ref(false)

// 新增标签
const addNewTag = () => {
  if (tag.value) {
    goodsInfo.value.tags.push(tag.value)
    tagVisible.value = false
    tag.value = ''
  }
}

// 增加商品
const addNewGoods = async (type) => {
  if (goodsInfo.value.identityId == null || goodsInfo.value.identityId === '') {
    ElMessage({
      message: '请选择发布身份',
      type: 'warning',
    })
    return
  }
  //构建表单对象
  const formData = new FormData()
  //将除了图片之外的属性添加到对象中
  for (let key in goodsInfo.value) {
    if (key !== 'images') {
      formData.append(key, goodsInfo.value[key])
    }
  }
  //将图片信息添加到formData中
  goodsInfo.value.images.forEach((item, index) => {
    formData.append(`images`, item.raw)
  })
  formData.append('saveCondition', type)
  //加载
  startLoading()
  //发送请求
  const res = (await addGoods(formData)).data
  //取消加载
  stopLoading()
  if (res.success) {
    ElNotification({
      title: '成功',
      message: '添加成功',
      type: 'success',
    })
    router.push('/shop/managegoods')
    clearForm()
  } else {
    ElNotification({
      title: '失败',
      message: `${res.errorMsg}`,
      type: 'error',
    })
  }
}

const clearForm = () => {
  goodsInfo.value = {
    name: '',
    description: '',
    price: 0,
    integral: 0,
    images: [],
    tags: [],
    number: 1,
    identityId: '',
  }
}
</script>

<style scoped less="scss">
.add-new-good {
  height: 600px;

  .edit {
    width: 100%;

    .title {
      font-size: 20px;
      margin: 10px 20px;
    }

    .sub-title {
      font-size: 18px;
      color: grey;
      margin: 15px 0 10px 0;
    }

    .images {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: start;

      height: 200px;
      margin-left: 15px;
    }

    .description {
      margin-left: 15px;

      .description {
        min-width: 800px;
      }

      .tags {
        display: flex;
        gap: 3px;
      }

      .description {
        font-size: 14px;
        color: grey;
      }

      .buttons {
        display: flex;
        justify-content: end;
        margin: 0 20px 10px 0;
      }
    }
  }
}
</style>
